import React, { Component } from 'react';
import { connect } from 'react-redux'
import { getCity, getHomeBanner, getList } from '../../api'
import actions from '../../store/actions';
import Banner from '../../components/Banner'
import { NavBar } from 'antd-mobile'
import { DownOutline } from 'antd-mobile-icons'
class Index extends Component {
  state = {
    banners: [],
    list: []
  }
  // 获取城市列表接口
  // 数据保存redux
  async getCity() {
    const { dispatch } = this.props
    const resp = await getCity()
    const action = actions.setCityList(resp.data.data)
    const action1 = actions.setCity(resp.data.data[0])
    dispatch(action)
    dispatch(action1)
  }
  // 获取首页轮播
  async getHomeBanner() {
    const resp = await getHomeBanner()
    console.log(resp.data);
    this.setState({
      banners: resp.data.data
    })
  }
  // 获取房源地址
  async getList() {
    const resp = await getList()
    this.setState({
      list: resp.data.data
    })

  }
  componentDidMount() {
    //获取城市列表
    this.props.cityList.length <= 0 && this.getCity()
    // 获取首页轮播
    this.getHomeBanner()
    //  获取列表数据
    this.getList()
  }
  render() {
    const { city } = this.props
    const { banners, list } = this.state
    return (
      <div>
        {/* 头部 */}
        <NavBar back={
          <div>
            { city.name }
            <DownOutline></DownOutline>
          </div>
        } onBack={ () => this.props.history.push('/city') } backArrow={false}>
          自如
        </NavBar>
        {/* 轮播 */}
        <Banner banners={ banners } height={200}></Banner>
        {/* 列表 */}
        <div className="list">
          {
            list.length>0 && list.map((v, i) => {
              return (
                <dl key={i} onClick={ () => this.props.history.push({ pathname: '/detail', state: v }) }>
                  <dt><img src={ v.banners[0] } alt="" /></dt>
                  <dd>
                    <h3>{ v.title }</h3>
                    <p>{v.desc}</p>
                    <h4>{v.pos.name}</h4>
                  </dd>
                </dl>
              )
            })
          }
        </div>
      </div>
    );
  }
}

const mapState = state => {
  return {
    ...state
  }
}

const mapDiapatch = dispatch => {
  return { dispatch }
}

export default connect(mapState, mapDiapatch)(Index);
